/** @format */

import SvgIcon from '@/components/SvgIcon/SvgIcon'

import styles from './Home.module.scss'
import { Popup, Tabs } from 'antd-mobile'
import useApiData from '@/hooks/useApiData'
import { getChannelListAsync } from '@/store/slice/home'
import { useState } from 'react'
import ChannelMgr from './components/ChannelMgr'
import type { ChannelItem } from '@/types/http'
import ArticleList from './components/ArticleList'
import { useNavigate } from 'react-router-dom'

const Home = () => {
  // 获取频道列表
  const { userChannels } = useApiData(getChannelListAsync, 'home')
  // 当前频道
  const [activeChannel, setActiveChannel] = useState('推荐')
  const [visible, setVisible] = useState(false)
  // 打开
  const onOpen = () => {
    setVisible(true)
  }
  // 关闭
  const onClose = () => {
    setVisible(false)
  }

  // 进入
  const onEnter = (item: ChannelItem) => {
    setActiveChannel(item.name)
    setVisible(false)
  }
  const navigate = useNavigate()

  return (
    <div className={styles.root}>
      {/* 频道 Tabs 列表 */}
      <Tabs
        className='tabs'
        defaultActiveKey={activeChannel}
        activeKey={activeChannel}
        onChange={(channel) => setActiveChannel(channel)}>
        {userChannels.map((item) => (
          <Tabs.Tab
            title={item.name}
            key={item.name}>
            <ArticleList channelId={item.id} />
          </Tabs.Tab>
        ))}
      </Tabs>
      <div className='tabs-opration'>
        <SvgIcon
          name='btn_search'
          onClick={() => navigate('/search')}
        />
        <SvgIcon
          name='btn_channel'
          onClick={onOpen}
        />
      </div>

      <Popup
        visible={visible}
        position='left'>
        <ChannelMgr
          onClose={onClose}
          onEnter={onEnter}
          activeChannel={activeChannel}
        />
      </Popup>
    </div>
  )
}

export default Home
